﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using AuctionHelper.Entity;
using System.Xml.Linq;

namespace AuctionHelper.Core
{
    /// <summary>
    /// Xml辅助类
    /// </summary>
    public class XmlHelper
    {
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T DeSerialize<T>()
        {
            var t = default(T);
            var path = ConfigHelper.GetDataFilePath<T>();
            var serializer = new XmlSerializer(typeof(T));
            using (var fileStream = new FileStream(path, FileMode.Open))
            {
                t = (T)serializer.Deserialize(fileStream);
                fileStream.Close();
                fileStream.Dispose();
            }
            return t;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T DeSerialize<T>(Stream stream)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            return (T)serializer.Deserialize(stream);
        }

        /// <summary>
        /// 反序列化列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> DeserializeList<T>()
        {
            var tList = (List<T>)Activator.CreateInstance(typeof(List<T>));
            var path = ConfigHelper.GetDataFilePath<T>();
            var xElement = XElement.Load(path);
            var xNodeList = xElement.Elements(typeof(T).Name).ToList();
            xNodeList.ForEach(x =>
            {
                using (var memoryStream = new MemoryStream())
                {
                    x.Save(memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    tList.Add(DeSerialize<T>(memoryStream));
                    memoryStream.Close();
                    memoryStream.Dispose();
                }
            });
            return tList;
        }
    }
}
